package com.sita.tingterest.activity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sita.bike.R;
import com.sita.tingterest.Implements.getCategoryJsonData;
import com.sita.tingterest.adapter.MusicListViewAdapter;
import com.sita.tingterest.pojo.Audio;
import com.sita.tingterest.pojo.Music;
import com.sita.tingterest.pojo.Pic;
import com.sita.tingterest.utils.L;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;

public class MusicPlayGridViewActivitys extends BaseActivity {
    public TextView tv_person;
    public ImageView imageView_music;
    public PullToRefreshListView music_ListView;
    public Intent intent;
    public int position;
    public String persion, img_url;
    public ImageButton imageButton_play;
    public ArrayList<Music> arrayListlist;
    //public MusicService mPlayService;
    public Context context;
    public static ArrayList<Music> musicList;
    public static ArrayList<Pic> picArrayList;
    public static ArrayList<Audio> audioArrayList;
    private Music music;
    private Pic pic;
    private Audio audio;
    public String content;
    public String catId;
    public MusicListViewAdapter gridViewAdapter;

    @Override
    public void onResume() {
        super.onResume();
        //isPause = false;

        L.l("MY sr", "onResume()" + "  ..Fragment Recommends;");
    }

    @Override
    public void onPause() {
        allowUnbindService();
        //isPause = true;
        L.l("MY sr", "onPause()" + "  ..Fragment Recommends;");
        super.onPause();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(getWindow().FEATURE_NO_TITLE);
        setContentView(R.layout.ting_activity_music_play_grid_view);
        allowBindService();
        initView();
        initData();
    }

    public void initView() {
        Intent intent = getIntent();
        catId = intent.getStringExtra("catId");
        imageButton_play = (ImageButton) findViewById(R.id.imageButton_play);
        tv_person = (TextView) findViewById(R.id.tv_persion);
        imageView_music = (ImageView) findViewById(R.id.image_title);
        music_ListView = (PullToRefreshListView)
                findViewById(R.id.music_listview);
    }

    public void initData() {


        DownLoadData downLoadData = (DownLoadData) new DownLoadData(new getCategoryJsonData() {
            @Override
            public void getCategoryData(String data) {
                arrayListlist = getJosonData(data);
                if (arrayListlist.size() <= 0) {
                    Toast.makeText(MusicPlayGridViewActivitys.this, "该分类无播放内容", Toast.LENGTH_LONG).show();
                } else {
                    content = data;
                    mPlayService.updateMusicList(arrayListlist);
                    setGridView(arrayListlist);
                }

            }
        }).execute("http://www.sitayun.com:8080/tinterest/v1/resources/list");

        imageButton_play.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                mPlayService.updateMusicList(getJosonData(content));
                imageButton_play.setImageResource(android.R.drawable.ic_media_pause);
                changePalyState();
            }
        });


    }

    public void changePalyState() {
        if (mPlayService.isPlaying()) {
            mPlayService.pausePlayer();
            imageButton_play.setImageResource(android.R.drawable.ic_media_play);
        } else {
            mPlayService.start();
            imageButton_play.setImageResource(android.R.drawable.ic_media_pause);
        }
    }

    public void setGridView(ArrayList<Music> list) {
        gridViewAdapter = new MusicListViewAdapter(MusicPlayGridViewActivitys.this, list);
        music_ListView.setAdapter(gridViewAdapter);
        music_ListView.setMode(PullToRefreshBase.Mode.BOTH);
        //设置下拉刷新标题
        music_ListView.getLoadingLayoutProxy(true, false).setPullLabel("正在刷新。。");
        music_ListView.getLoadingLayoutProxy(true, false).setRefreshingLabel("正在刷新。。");
        music_ListView.getLoadingLayoutProxy(true, false).setReleaseLabel("刷新。。。");
        //设置上拉加载标题
        music_ListView.getLoadingLayoutProxy(false, true).setPullLabel("正在加载");
        music_ListView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在努力加载");
        music_ListView.getLoadingLayoutProxy(false, true).setReleaseLabel("放手加载更多");
        music_ListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String url = arrayListlist.get(position - 1).getPic().getUrl();
                if (url != null) {
                    ImageLoader.getInstance().displayImage(url, imageView_music);
                }
                tv_person.setText(arrayListlist.get(position - 1).getTitle());
                mPlayService.play(position - 1);
                Log.i("MusicPlay", "play" + position);
                imageButton_play.setImageResource(android.R.drawable.ic_media_pause);
            }
        });

    }

    //解析json字符串
    private ArrayList<Music> getJosonData(String contents) {
        JSONObject jsonObject = null;
        JSONArray jsonArray = null;
        String title = null;
        String picUrl = null;
        String audiolink = null;
        final String content;
        try {
            jsonObject = new JSONObject(contents);
            jsonArray = jsonObject.getJSONArray("data");
            musicList = new ArrayList<Music>();
            picArrayList = new ArrayList<Pic>();
            audioArrayList = new ArrayList<Audio>();
            for (int i = 0; i < jsonArray.length(); i++) {
                music = new Music();
                pic = new Pic();
                audio = new Audio();
                //获取title
                JSONObject jsonObjectContent = jsonArray.getJSONObject(i);
                title = jsonObjectContent.getString("title");
                music.setTitle(title);
                musicList.add(music);
                //获取图片Url
                JSONArray jsonArrayPic = jsonObjectContent.getJSONArray("pic");
                JSONObject jsonObjectPic = jsonArrayPic.getJSONObject(0);
                picUrl = jsonObjectPic.getString("url");
                pic.setUrl(picUrl);
                music.setPic(pic);
                //获取AudioUrl
                JSONArray jsonArrayAudio = jsonObjectContent.getJSONArray("audio");
                JSONObject jsonObjectAudio = jsonArrayAudio.getJSONObject(0);
                audiolink = jsonObjectAudio.getString("link");
                audio.setUrl(audiolink);
                music.setAudio(audio);
            }

        } catch (JSONException e) {
            e.printStackTrace();
        }
        return musicList;
    }

    public static String submitPostData(String url, String catId) {
        String result = "";
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            //添加http头信息
            httppost.addHeader("Accept", "application/json"); //认证token
            httppost.addHeader("Content-Type", "application/json");
            //http post的json数据格式：  {"name": "your name","parentId": "id_of_parent"}
            JSONObject obj = new JSONObject();
            //obj.put("accountId","1");
            obj.put("catId", catId);
            httppost.setEntity(new StringEntity(obj.toString()));
            HttpResponse response;
            response = httpclient.execute(httppost);
            //检验状态码，如果成功接收数据
            int code = response.getStatusLine().getStatusCode();
            if (code == 200) {
                result = EntityUtils.toString(response.getEntity());
            }
        } catch (ClientProtocolException e) {
        } catch (IOException e) {
            Log.i("sd", "" + e);
        } catch (Exception e) {
            Log.i("ss", "" + e);
        }
        return result;
    }

    //创建服务连接
    /*private ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mPlayService = ((MusicService.MyMusicBinder) service).getServices();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mPlayService = null;
        }
    };*/

    /*public void allowBindService() {
        Log.i("MY sr", "allowBindService()");
        this.bindService(new Intent(MusicPlayGridViewActivity.this, MusicService.class), serviceConnection,
                Context.BIND_AUTO_CREATE);
    }*/

    /**
     * fragment的view消失后回调
     */
    /*public void allowUnbindService() {
        Log.i("MY sr", "allowUnbindService()");
        this.unbindService(serviceConnection);
    }*/

   /* private void onItemPlay(int position) {
        // if(!mActivity.getPlayService().isPlaying()) return;
        music_ListView.smoothScrollToPosition(position);
        // 获取上次播放的位置
        int prePlayingPosition = gridViewAdapter.getPlayingPosition();
        // 如果上次播放的位置在可视区域内
        // 则手动设置invisible
        if (prePlayingPosition >= music_ListView.getFirstVisiblePosition()
                && prePlayingPosition <= music_ListView.getLastVisiblePosition()) {
            int preItem = prePlayingPosition - music_ListView.getFirstVisiblePosition();
            ((ViewGroup) music_ListView.getChildAt(preItem)).getChildAt(0).setVisibility(
                    View.INVISIBLE);
        }
        // 设置新的播放位置
        gridViewAdapter.setPlayingPosition(position);

        // 如果新的播放位置不在可视区域
        // 则直接返回
        if (music_ListView.getLastVisiblePosition() < position
                || music_ListView.getFirstVisiblePosition() > position)
            return;

        // 如果在可视区域
        // 手动设置改item visible
        int currentItem = position - music_ListView.getFirstVisiblePosition();
        ((ViewGroup) music_ListView.getChildAt(currentItem)).getChildAt(0)
                .setVisibility(View.VISIBLE);
    }*/
    @Override
    protected void onChange(int position) {
    }

    @Override
    protected void onPublish(int progress) {

    }

    private class DownLoadData extends AsyncTask<String, Integer, String> {
        public getCategoryJsonData getCategoryData;

        public DownLoadData() {
        }

        public DownLoadData(getCategoryJsonData getCategoryData) {
            this.getCategoryData = getCategoryData;
        }

        @Override
        protected String doInBackground(String... params) {
            String content = submitPostData(params[0], catId);
            return content;
        }

        @Override
        protected void onPostExecute(String s) {
            getCategoryData.getCategoryData(s);
        }
    }


}
